package com.obj.commpont.common.captcha.util;

import java.awt.*;
import java.util.Random;

/**
 * 图片验证码随机数工具类
 *
 * @author yuan 2018/12/3 13:57
 */
public class CaptchaRandomUtils {

    /**
     * 去掉了1,0,i,o,g几个容易混淆的字符
     */
    public static final String CAPTCHA_CODE = "23456789abcdefhgklmnpqrstuvwxyzABCDEFHGKLMNPQRSTUVWXYZ";

    private static final Random random = new Random();

    /**
     * 方法的描述： 随机生成随字符串
     *
     * @param str    指定的字符串
     * @param length 字符串的个数
     * @return string
     */
    public static String getRandomString(String str, int length) {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < length; i++) {
            int number = random.nextInt(str.length());
            sb.append(str.charAt(number));
        }
        return sb.toString();
    }

    /**
     * 方法的描述： 随机生成随字符串
     *
     * @param length 字符串的个数
     * @return string
     */
    public static String getCaptchaCode(int length) {
        return getRandomString(CAPTCHA_CODE, length);
    }

    /**
     * 生成指定范围的随机数
     *
     * @param min 最小范围
     * @param max 最大范围
     * @retrun 数值
     */
    public static int randomNum(int min, int max) {
        return (int) Math.floor(Math.random() * (max - min) + min);
    }

    /**
     * 生成指定范围的随机数
     *
     * @param max 最大范围
     * @retrun 数值
     */
    public static int randomNum(int max) {
        return randomNum(0, max);
    }

    /**
     * 随机生成RGB颜色
     */
    public static Color getRundomRgb(int pr, int pg) {
        if (pr > 255) {
            pr = 255;
        }
        if (pg > 255) {
            pg = 255;
        }
        int r = pr + random.nextInt(pg - pr);
        int g = pr + random.nextInt(pg - pr);
        int b = pr + random.nextInt(pg - pr);
        return new Color(r, g, b);
    }

    /**
     * 随机画干扰线
     *
     * @param num 数量
     * @param g2  Graphics2D
     */
    public static void drawLine(int num, Graphics2D g2, int width, int height) {
        for (int i = 0; i < num; i++) {
            g2.setColor(getRundomRgb(150, 250));
            int x1 = randomNum((-10), width - 10);
            int y1 = randomNum(5, height - 5);
            int x2 = randomNum(10, width + 10);
            int y2 = randomNum(2, height - 2);
            g2.drawLine(x1, y1, x2, y2);
        }
    }

    /**
     * 随机画干扰圆
     *
     * @param num 数量
     * @param g2  Graphics2D
     */
    public static void drawOval(int num, Graphics2D g2, int width, int height) {
        for (int i = 0; i < num; i++) {
            g2.setColor(getRundomRgb(100, 250));
            g2.drawOval(randomNum(width), randomNum(height), 10 + randomNum(20), 10 + randomNum(20));
        }
    }

}
